package com.vova.rec.grpc.server;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.vova.rec.grpc.common.BooleanReply;
import com.vova.rec.grpc.common.ConditionsRequest;
import com.vova.rec.grpc.common.DeviceFix;
import com.vova.rec.grpc.common.DeviceFixServiceGrpc;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@GrpcService
public class DeviceFixServiceGrpcImpl extends DeviceFixServiceGrpc.DeviceFixServiceImplBase {

    private final ConcurrentMap<String, DeviceFix> db = new ConcurrentHashMap<>();

//    @Autowired
//    private ScopedBean scopedBean;

    @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
    private boolean useLocalCache;

    @Override
    public void insertDeviceFix(DeviceFix request, StreamObserver<BooleanReply> responseObserver) {
        log.info("---> insert={}", request);
        boolean isExist = db.putIfAbsent(request.getId(), request) == null;
        BooleanReply booleanReply = BooleanReply.newBuilder().setReply(isExist).build();
//        log.info("---> scopedBean={}", scopedBean.getCurrent());
        log.info("---> nacosConfig useLocalCache={}", useLocalCache);
        responseObserver.onNext(booleanReply);
        responseObserver.onCompleted();
    }

    @Override
    public void updateDeviceFix(DeviceFix request, StreamObserver<BooleanReply> responseObserver) {
        log.info("---> update={}", request);
        db.put(request.getId(), request);
        BooleanReply booleanReply = BooleanReply.newBuilder().setReply(true).build();
        responseObserver.onNext(booleanReply);
        responseObserver.onCompleted();
    }

    @Override
    public void searchDeviceFix(ConditionsRequest request, StreamObserver<DeviceFix> responseObserver) {
        log.info("---> search={}", request);
        DeviceFix deviceFix = db.get(request.getId());
        responseObserver.onNext(deviceFix);
        responseObserver.onCompleted();
    }

    @Override
    public void deleteDeviceFix(ConditionsRequest request, StreamObserver<BooleanReply> responseObserver) {
        log.info("---> delete={}", request);
        boolean success = db.remove(request.getId()) == null;
        BooleanReply booleanReply = BooleanReply.newBuilder().setReply(success).build();
        responseObserver.onNext(booleanReply);
        responseObserver.onCompleted();
    }
}
